package service;

import dao.ArticleOperation;
import utils.JdbcUtils;
import pojo.Article;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author fire'ge
 */
public  class ArticlesService {
    public static List<Article> getArticleList() throws SQLException, IOException {
        Connection connection = JdbcUtils.getConnection();
        ResultSet resultSet = ArticleOperation.checkArticles(connection);
        int id;
        String topic,text,author;
        List<Article> articles = new ArrayList<>();
        while (resultSet.next()){
            id = resultSet.getInt(1);
            topic = resultSet.getString(2);
            text = resultSet.getString(3);
            author = resultSet.getString(4);
            articles.add(new Article(id,topic,text,author));
        }
        connection.close();
        return articles;
    }
    public static Article getArticle(int id) throws SQLException, IOException {
        Connection connection = JdbcUtils.getConnection();
        ResultSet resultSet = ArticleOperation.displayArticle(id,connection);
        Article article = null;
        while (resultSet.next()){
            article = new Article(resultSet.getInt(1),
                    resultSet.getString(2),
                    resultSet.getString(3),
                    resultSet.getString(4));
        }
        resultSet.close();
        connection.close();
        return article;
    }
    public static Boolean addArticle(String topic,String text,String author) throws SQLException, IOException {
        Connection connection = JdbcUtils.getConnection();
        boolean isUpdate = ArticleOperation.addArticle(topic, text, author, connection);
        connection.close();
        return isUpdate;
    }
}
